﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Linq;

namespace Pay.Service.Service {
    public class MerchantDeclarationService : ServiceBase, IMerchantDeclarationService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ISettingService _settingService;
        private IMerchantService _merchantService;

        public MerchantDeclarationService(IUnitOfWork iUnitOfWork, ISettingService settingService, IMerchantService merchantService)
             : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _settingService = settingService;
            _merchantService = merchantService;
        }

        public int SaveMerchantDeclaration(merchant_declaration_dto dto) {
            var merchant = dto.ToDtoObject<MerchantDeclaration>();
            var merchant_dec = context.MerchantDeclarations.FindById(dto.id).ToDtoObject<merchant_declaration_dto>();
            if (merchant_dec == null) {
                merchant.AuthStatus = MerchantDeclarationStatusEnums.Fee;
                merchant.CreateTime = DateTime.Now.ToUnix();
                context.MerchantDeclarations.Add(merchant);
            } 
            int result = _iUnitOfWork.Commit("MerchantDeclaration");
            return result;
        }

        public int AuditMerchantDeclaration(merchant_declaration_dto dto) {
            var merchant = context.MerchantDeclarations.FirstOrDefault(c => c.Id == dto.id);
            merchant.AuthStatus = dto.auth_status;
            var result = _iUnitOfWork.Commit("MerchantDeclaration");
            return result;
        }



        /// <summary>
        /// 供应商申报状态更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public int UpdateMerchantDeclarationStatus(long id, MerchantDeclarationStatusEnums status) {
            var merchant_dec = context.MerchantDeclarations.Find(id);
            var merchant = _merchantService.Get(id);
            if (merchant.is_oem == true) {
                merchant_dec.AuthStatus = status;
            } else {
                if ((int)status > (int)MerchantDeclarationStatusEnums.Wait) {
                    throw new Exception("无相应操作权限");
                } else {
                    merchant_dec.AuthStatus = status;
                }
            }
            int result = _iUnitOfWork.Commit("MerchantDeclaration" + id);
            return result;
        }

        /// <summary>
        /// 首页-供应商资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public merchant_declaration_dto_ex GetMerchantInfo(long id) {
            var merchant_dec = context.MerchantDeclarations.Where(c => c.Id == id).FromCacheFirstOrDefault<MerchantDeclaration, merchant_declaration_dto>("MerchantDeclaration" + id);
            var merchant = _merchantService.Get(id);
            var merchant_ex = new merchant_declaration_dto_ex();
            if (merchant_dec != null) {
                if (merchant_dec.review_time.ToUnix() > 0)
                    merchant_ex.effective_time = (merchant_dec.review_time.Year - merchant_dec.create_time.Year) * 365;
                else
                    merchant_ex.effective_time = 0;
                merchant_ex.fee_count = merchant_dec.fee_count;
                merchant_ex.certification_status = (int)merchant_dec.auth_status;
                merchant_ex.merchant_name = merchant_dec.name;
            } else {
                merchant_ex.effective_time = 0;
                merchant_ex.fee_count = 0;
                merchant_ex.certification_status = 0;
                merchant_ex.merchant_name = merchant.name;
            }
            return merchant_ex;
        }

        /// <summary>
        /// 获取供应商审核状态
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public int GetMerchantDeclarationStatus(long user_id) {
            var merchant_dec = context.MerchantDeclarations.Where(c => c.Id == user_id).FromCacheFirstOrDefault<MerchantDeclaration, merchant_declaration_dto>("MerchantDeclaration" + user_id);
            int status;
            if (merchant_dec != null)
                status = (int)merchant_dec.auth_status;
            else
                status = 0;
            return status;
        }

        /// <summary>
        /// 获取oem认证信息
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public merchant_certification_dto GetMerchantCertification(long user_id) {
            var merchant = context.Merchants.FindById(user_id);
            var merchant_dec_num = context.MerchantDeclarations.Where(c => c.AuthStatus == MerchantDeclarationStatusEnums.Wait).Count();
            var good_dec_num = context.GoodDeclarations.Where(c => c.AuditStatus == GoodDeclarationStatusEnums.Wait).Count();
            var merchant_cer = context.MerchantCertifications.FindById(user_id);
            if (!merchant.IsOEM)
                throw new ServerErrorException("用户不是后台管理员");
            if (merchant_cer == null) {
                return new merchant_certification_dto() {certifications_num = 0, filing_num = 0, un_certifications_num = merchant_dec_num, un_filing_num = good_dec_num};
            }
            return merchant_cer.ToDtoObject<merchant_certification_dto>();
        }

        /// <summary>
        /// 获取商户申报列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<merchant_declaration_dto> GetMerchantDeclarations(MerchantDeclarationQuery query) {
            var filter = PredicateBuilder.True<MerchantDeclaration>();
            int auth_status = Convert.ToInt32(query.auth_status);
            if (!String.IsNullOrEmpty(query.name))
                filter = filter.And(c => c.MerchantName.Contains(query.name));
            if (!String.IsNullOrEmpty(query.auth_status))
                filter = filter.And(c => c.AuthStatus == (MerchantDeclarationStatusEnums)auth_status);
            var start_time = query.start_time.ToUnix();
            if (query.start_time.HasValue && query.end_time.HasValue) {
                var end_time = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime >= start_time && c.CreateTime <= end_time);
            } else if (query.start_time.HasValue && !query.end_time.HasValue)
                filter = filter.And(c => c.CreateTime >= start_time);
            else if (!query.start_time.HasValue && query.end_time.HasValue) {
                var end_time = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime <= end_time);
            }
            var result = context.MerchantDeclarations.FromCachePaged<MerchantDeclaration, merchant_declaration_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.Id), "MerchantDeclaration");
            return result;
        }
    }
}
